import hashlib
import time

import requests
from django.conf import settings
from django.core.cache import cache

from libs.wx.utils import PayUtil
from public.constants import logger


def get_access_token():
    access_token = cache.get('xcx_access_token')
    if access_token:
        return access_token
    params = {
        'grant_type': 'client_credential',
        'appid': settings.SERVICES['WX_SET']['APP_ID'],
        'secret': settings.SERVICES['WX_SET']['APP_SECRET']
    }
    res = requests.post('https://api.weixin.qq.com/cgi-bin/stable_token', json=params).json()
    if res['access_token']:
        cache.set('xcx_access_token', res['access_token'], res['expires_in'] - 600)
    else:
        raise Exception(f'get access token error: {res}')
    return res['access_token']


def get_jsapi_ticket():
    jsapi_ticket = cache.get('jsapi_ticket')
    if jsapi_ticket:
        return jsapi_ticket
    access_token = get_access_token()
    res = requests.get(
        f'https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={access_token}&type=jsapi'
    ).json()
    if res['ticket']:
        cache.set('jsapi_ticket', res['ticket'], res['expires_in'] - 600)
    else:
        raise Exception(f'get jsapi ticket error: {res}')
    return res['ticket']


def make_js_sdk_config(url):
    jsapi_ticket = get_jsapi_ticket()
    params = {
        'jsapi_ticket': jsapi_ticket,
        'noncestr': PayUtil.nonce_str(),
        'timestamp': int(time.time()),
        'url': url
    }
    string1 = '&'.join([f'{k}={v}' for k, v in sorted(params.items())])
    sign = hashlib.sha1(string1.encode('utf-8')).hexdigest()
    return {
        'appId': settings.SERVICES['WX_SET']['APP_ID'],
        'timestamp': params['timestamp'],
        'nonceStr': params['noncestr'],
        'signature': sign,
        'jsApiList': [
            'scanQRCode',
            'chooseWXPay'
        ]
    }


def send_template_message(form_id, template_id, openid, data=None, page=None, emphasis_keyword=None):
    params = {
        'access_token': get_access_token(),
        'touser': openid,
        'template_id': template_id,
        'form_id': form_id,
        'data': data,
        'page': page,
        'emphasis_keyword': emphasis_keyword,
    }
    res = requests.post('https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send', json=params).json()
    if res['errcode'] != 0:
        logger.error(f'send template error: {res}')


def get_wxa_code(path, width=430):
    params = {'path': path, 'width': width}
    api = f'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token={get_access_token()}'
    res = requests.post(api, json=params)
    return res.content


def get_unlimited_code(scene, page=None, width=430):
    params = {'page': page, 'scene': scene, 'width': width}
    api = f'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token={get_access_token()}'
    res = requests.post(api, json=params)
    return res.content
